define(function (require, exports, module) {
    'use strict';
    var $ = require('jquery'),
        _ = require('underscore'),
        Backbone = require('backbone'),
        notify = require('js/utils/notify'),
        models = require('js/apps/stats/models'),
        opModelCls = require('js/apps/op/models'),
        utils = require('js/utils/tools'),
        chart = require('js/utils/chart'),
        helper = require('js/apps/report/common'),
        datebox = require('js/apps/report/datebox'),
        moment = require('moment'),
        app = Backbone.history;
    require('magnific');
    require('multiselect');

    var AccountDetailView = Backbone.View.extend({
        template: "stats/AccountDetail.html",
        initialize: function (options) {
            this.id = options.id;
            this.model = new models.Account();
            if (this.id) this.model.set('id', this.id)
            this.model.bind('change', this.renderWithData, this);
        },
        render: function () {
            this.$el.html("");
            $(window).scrollTop(0);
            return this;
        },
        load: function (options) {
            if (this.id != null) {
                this.model.fetch({
                    reset: true,
                    error: function (c, r, o) {
                        notify.notifyResp(r);
                        $('#content').append('<h4 class="text-muted">无数据</h4>');
                    },
                    success: function (c, r, o) {
                        if (options.callback) {
                            options.callback();
                        }
                    }
                });
            } else {
                this.renderWithData();
            }
        },
        renderWithData: function () {
            console.log(this.model.toJSON())
            this.$el.html(this.template(this.model.toJSON()));

            var that = this;

            var pay_stats = this.model.toJSON().user_stats.pay || {},
                refund_stats = this.model.toJSON().user_stats.refund || {};

            var options1 = chart.getHighChartPieOptions();
            options1.title.text = '购彩分布';
            options1.series[0].data = [];
            _.each(window.LOTTERY_TYPE, function(v, k){
                var amount = pay_stats[k.toString()],
                    refund = refund_stats[k.toString()];
                if(!refund) refund = 0;
                if(!amount) amount = 0;
                if(amount){
                    options1.series[0].data.push([v, Math.round(amount - refund)])
                }
            });
            $('#pay-dist').highcharts(options1);

            var daily_pay_stats = this.model.toJSON().daily_stats.pay || {},
                daily_refund_stats = this.model.toJSON().daily_stats.refund || {};

            var daily_options1 = chart.getHighChartPieOptions();
            daily_options1.title.text = '购彩分布';
            daily_options1.series[0].data = [];
            _.each(window.LOTTERY_TYPE, function(v, k){
                var daily_amount = daily_pay_stats[k.toString()],
                    daily_refund = daily_refund_stats[k.toString()];
                if(!daily_refund) daily_refund = 0;
                if(!daily_amount) daily_amount = 0;
                if(daily_amount){
                    daily_options1.series[0].data.push([v, Math.round(daily_amount - daily_refund)])
                }
            });
            $('#daily-pay-dist').highcharts(daily_options1);


            var win_stats = this.model.toJSON().user_stats.win || {};
            var options2 = chart.getHighChartPieOptions();
            options2.title.text = '中奖分布';
            options2.series[0].data = [];
            _.each(window.LOTTERY_TYPE, function(v, k){
                var amount = win_stats[k.toString()];

                if(amount){
                    options2.series[0].data.push([v, Math.round(amount)])
                }
            });
            $('#win-dist').highcharts(options2);

            var bonus_stats = this.model.toJSON().user_stats.bonus || {};
            var options3 = chart.getHighChartPieOptions();
            options3.title.text = '加奖分布';
            options3.series[0].data = [];
            _.each(window.LOTTERY_TYPE, function(v, k){
                var amount = bonus_stats[k.toString()];
                if (amount){
                    options3.series[0].data.push([v, Math.round(amount)])
                }
            });
            $('#bonus-dist').highcharts(options3);

            return this;
        },
    });
    var AccountCouponListView = Backbone.View.extend({
        tagName: "div",
        className: "p25 pt35",
        template: "stats/AccountCoupon.html",
        initialize: function (options) {
            this.options = options;
            this.collection = new models.AccountCouponCollection(options);
            this.coupons = new opModelCls.CouponTemplateCollection();
            this.collection.bind('change remove reset', this.renderWithData, this);
            this.coupons.bind('change remove reset', this.renderWithData, this);
        },
        render: function () {
            this.$el.html("");
            return this;
        },
        renderWithData: function () {
            this.$el.html(this.template({
                items: this.collection.toJSON(),
                coupons: this.coupons.toJSON(),
                stats: this.collection.stats
            }));
            var that = this;
            utils.renderTable('account-coupon-list', {
                $orderby: that.options.$orderby || 'id',
                sortCallback: function (field) {
                    that.options.$orderby = field;
                    that.options.$page = 1;
                    that.collection.fetch({
                        reset: true,
                        data: that.options
                    });
                }
            });
            $('#addCoupon').magnificPopup({
                items: {
                    src: '#addCouponPanel',
                    type: 'inline'
                },
                midClick: true,
                closeOnBgClick: false,
                // showCloseBtn: false,
                callbacks: {
                    beforeOpen: function () {
                        $('#submitAdd').off('click').click(function () {
                            var options = {
                                template_id: parseInt($("#inputCoupon").val()),
                                user_id: that.options.user_id,
                                count: parseInt($('#inputCount').val(), 10)
                            };
                            $.magnificPopup.close();
                            $.post('admin/coupon/add/', JSON.stringify(options)).fail(function (data) {
                                notify.notifyResp(data);
                            }).then(function (data) {
                                notify.success();
                                that.collection.fetch({
                                    reset: true,
                                    data: that.options
                                })
                            });
                        });
                    },

                }
            });
            utils.multiselect('#inputCoupon', true);
            $('#paginator').bootstrapPaginator({
                currentPage: this.options.$page,
                totalPages: Math.ceil(this.collection.total / 5) || 1,
                size: 'small',
                numberOfPages: 10,
                alignment: 'center',
                onPageClicked: function (e, originalEvent, type, page) {
                    e.stopImmediatePropagation();
                    that.options.$page = page;
                    that.collection.fetch({
                        reset: true,
                        data: that.options
                    });
                }
            });
            return this;
        },
        load: function () {
            this.collection.fetch({
                reset: true,
                data: this.options,
            });
            this.coupons.fetch({
                reset: true,
                data: {
                    $size: -1
                }
            });
        }
    });
    var AccountTransactionView = Backbone.View.extend({
        tagName: "div",
        className: "p25 pt35",
        template: "stats/AccountTransaction.html",
        events: {
            'click #search': 'doSearch',
        },
        initialize: function (options) {
            this.options = options;
            this.collection = new models.AccountTransactionCollection(options);
            this.collection.bind('change remove reset', this.renderWithData, this);
        },
        render: function () {
            this.$el.html("");
            return this;
        },
        doSearch: function (){

            delete this.options.title;
            var selectedType = parseInt($('#searchType').val());
            this.options.title = utils.getInput('#searchTitle') || [];

            var timeRange = helper.getDateRange();

            if(this.options.title && this.options.title.length > 0) {
                this.options.title = JSON.stringify({ '$in': this.options.title });
            }
            if(selectedType) {
                if (selectedType > 0) {
                    this.options.price = JSON.stringify({'$gte': 0});
                }
                else {
                    this.options.price = JSON.stringify({'$lte': 0});
                }
            }
            else
                delete this.options.price;
            this.options.dateRange = timeRange;
            this.options.updated_at = JSON.stringify({'$gte': timeRange[0], '$lte': timeRange[1]});
            this.load();
        },
        renderWithData: function () {
            if(!this.options.price) var price = 0;
            else var price = parseInt($('#searchType').val());
            if(!this.options.title) var title = -1;
            else var title = $('#searchTitle').val();

            // add coupon price to pay price
            _.each(this.collection.models, function(data) {
                if(data.attributes.extend){
                    var extend = JSON.parse(data.attributes.extend);
                    if(extend.hasOwnProperty('coupon_price')){
                        data.attributes.price = parseInt(data.attributes.price) - parseInt(extend.coupon_price);
                        data.attributes.coupon = extend.coupon_price;
                    }
                }
            });
            this.$el.html(this.template({
                items: this.collection.toJSON(),
                titles: this.collection.titles,
                searched: {
                    'price': price,
                    'title': title
                }
            }));
            var that = this;

            helper.loadDatePicker(this.options, true);
            utils.multiselect('#searchTitle', true, {
                'includeSelectAllOption': true
            });

            utils.renderTable('account-transaction-list', {
                $orderby: that.options.$orderby || '-created_at',
                sortCallback: function (field) {
                    that.options.$orderby = field;
                    that.options.$page = 1;
                    that.collection.fetch({
                        reset: true,
                        data: that.options
                    });
                }
            });
            $('#trans-paginator').bootstrapPaginator({
                currentPage: this.options.$page,
                totalPages: Math.ceil(this.collection.total / 5) || 1,
                size: 'small',
                numberOfPages: 10,
                alignment: 'center',
                onPageClicked: function (e, originalEvent, type, page) {
                    e.stopImmediatePropagation();
                    that.options.$page = page;
                    that.collection.fetch({
                        reset: true,
                        data: that.options
                    });
                }
            });
            return this;
        },
        load: function () {
            this.collection.fetch({
                reset: true,
                data: this.options,
            });
        }
    });
    exports.List = Backbone.View.extend({
        el: "#content_wrapper",
        template: "stats/AccountPage.html",
        events: {
            'click #search': 'doSearch',
        },
        initialize: function (options) {
            this.options = options;
        },
        doSearch: function () {
            // 先判断有没有填写user_name
            var user_name = $('#searchUserName').val();
            if(user_name){
                $.ajax({
                    type: 'GET',
                    url: '/admin/get_user_id/?user_name=' + user_name,
                    async: false,
                    success: function (result){
                        var data = result.data;
                        if(data.user_id){
                            $('#searchId').val(data.user_id);
                        }else{
                            alert('不存在用户: '+ user_name);
                        }
                    }
                });
            }

            var phone = $('#searchPhone').val();
            if(phone){
                $.ajax({
                    type: 'GET',
                    url: '/admin/get_user_id/?phone=' + phone,
                    async: false,
                    success: function (result){
                        var data = result.data;
                        if(data.user_id){
                            $('#searchId').val(data.user_id);
                        }else{
                            alert('不存在手机: ' + phone);
                        }
                    }
                });
            }

            var options = {},
                searched = {};
            searched.id = parseInt($('#searchId').val());

            if (!isNaN(searched.id)) {
                options.id = searched.id;
                utils.saveSearched('stats/account', searched);
                app.navigate('#stats/account/?id=' + searched.id, {
                    trigger: true
                });
            }
        },
        render: function () {
            this.$el.html(this.template({
                searched: utils.getSearched('stats/account')
            }));
            var today = moment().endOf('day').format('YYYY-MM-DD HH:mm'),
                minDate = moment().format('YYYY-MM-DD'),
                timeRange = [minDate,today],
                updated_at = JSON.stringify({'$gte': minDate, '$lte': today});

            var section = this.$el.find('#content');
            if (this.options.id != null) {
                var detailView = new AccountDetailView(this.options),
                    couponList = new AccountCouponListView({
                        'user_id': this.options.id,
                        'status': 1,
                        '$page': 1,
                        '$size': 5,
                        '$orderby': '-id'
                    }),
                    transactionList = new AccountTransactionView({
                        'user_id': this.options.id,
                        '$page': 1,
                        '$size': 5,
                        '$orderby': '-created_at',
                        'updated_at': updated_at,
                        'dateRange': timeRange
                    });
                
                $(section).append(detailView.render().el);
                detailView.load({
                    callback: function () {
                        $(section).append(couponList.render().el);
                        couponList.load();
                        // $(section).append(transactionList.render().el);
                        // transactionList.load();
                    }
                });
            } else {
                $(section).append('<h4 class="text-muted">请从右侧进行搜索...</h4>');
            }
            return this;
        }
    });
    exports.Views = [AccountDetailView, AccountCouponListView, AccountTransactionView];
});